﻿using System.IO;
using System.Net.Http;
using System.Threading;
using HighPerformanceLog.V2;

namespace ProcessBarDemo.UpdateFramework
{
    public static class DownloadService
    {
        public static double process = 0;
        public static void DownloadFile(string url, string saveDir, int threadCount, long fileSize, string fileName)
        {
            string fullPath = Path.Combine(saveDir, fileName);

            if (threadCount <= 1 || fileSize < 1024 * 1024)
            {
                SegmentDownloader.Download(url, 0, fileSize - 1, fullPath);
                return;
            }

            long partSize = fileSize / threadCount;
            Thread[] threads = new Thread[threadCount];
            string[] partFiles = new string[threadCount];

            for (int i = 0; i < threadCount; i++)
            {
                long start = partSize * i;
                long end = (i == threadCount - 1) ? fileSize - 1 : start + partSize - 1;
                string partFile = Path.Combine(saveDir, $"{fileName}.part{i}");
                partFiles[i] = partFile;

                threads[i] = new Thread(() => SegmentDownloader.Download(url, start, end, partFile));
                threads[i].Start();
            }

            foreach (var t in threads) t.Join();
            FileMerger.Merge(partFiles, fullPath);
        }
    }
}
